<template>
    <div class="mobile-attachment-container">
      <!-- 图片列表 -->
      <div class="image-list" v-loading="loading">
        <div
          v-for="(item, index) in dataList"
          :key="item.id"
          class="image-item"
          :class="{ 'clickable': index === 0, 'non-clickable': index !== 0 }"
          @click="previewImage(item, index)"
        >
          <!-- 图片 -->
          <div class="image-wrapper">
            <el-image
              :src="item.url"
              :alt="item.name"
              fit="contain"
              loading="lazy"
              @error="handleImageError"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
          </div>
          

        </div>
      </div>
  
      <!-- 空状态 -->
      <el-empty
        v-if="dataList.length === 0 && !loading"
        description="暂无图片数据"
      />
  
      <!-- 加载更多 -->
      <div v-if="hasMore" class="load-more">
        <el-button
          :loading="loadingMore"
          @click="loadMore"
          text
          type="primary"
        >
          {{ loadingMore ? '加载中...' : '加载更多' }}
        </el-button>
      </div>
  
      <!-- 图片预览 -->
      <el-image-viewer
        v-if="showViewer"
        :url-list="previewUrls"
        :initial-index="previewIndex"
        @close="showViewer = false"
      />

      <!-- 用户信息弹框 -->
      <el-dialog
        v-model="showUserDialog"
        title=""
        width="90%"
        :show-close="false"
        :close-on-click-modal="true"
        @close="closeUserDialog"
        class="user-dialog"
      >
        <div class="dialog-content">
          <!-- 上半部分：图片展示 -->
          <div class="image-section">
            <img src="/images/add.png" alt="服务图片" class="service-image" />
          </div>
          
          <!-- 下半部分：表单 -->
          <div class="form-section">
            <div class="form-content">
              <el-form :model="userForm" :rules="formRules" ref="userFormRef" label-width="60px" style="margin-left: 0; text-align: left;">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="userForm.name" placeholder="请输入姓名" />
                </el-form-item>
                
                <el-form-item label="电话" prop="phone">
                  <el-input v-model="userForm.phone" placeholder="请输入电话号码" />
                </el-form-item>
                
                <el-form-item label="地区" prop="region">
                  <div class="region-inputs">
                    <select v-model="userForm.province" @change="handleProvinceChange" style="width: 30%; height: 24px; border: 1px solid #dcdfe6; border-radius: 2px; padding: 0 2px; margin-right: 3px; font-size: 11px; background-color: white;">
                      <option value="">省</option>
                      <option v-for="(province, index) in provinceList" :key="index" :value="province">
                        {{ province }}
                      </option>
                    </select>
                    <select v-model="userForm.city" @change="handleCityChange" :disabled="!userForm.province" style="width: 30%; height: 24px; border: 1px solid #dcdfe6; border-radius: 2px; padding: 0 2px; margin-right: 3px; font-size: 11px; background-color: white;">
                      <option value="">市</option>
                      <option v-for="(city, index) in cityList" :key="index" :value="city">
                        {{ city }}
                      </option>
                    </select>
                    <select v-model="userForm.district" :disabled="!userForm.city" style="width: 30%; height: 24px; border: 1px solid #dcdfe6; border-radius: 2px; padding: 0 2px; font-size: 11px; background-color: white;">
                      <option value="">区/县</option>
                      <option v-for="(district, index) in districtList" :key="index" :value="district">
                        {{ district }}
                      </option>
                    </select>
                  </div>
                </el-form-item>
                
                <el-form-item label="地址" prop="address">
                  <el-input v-model="userForm.address" placeholder="请输入详细地址" />
                </el-form-item>
                
                <el-form-item label="备注" prop="remark">
                  <el-input 
                    v-model="userForm.remark" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入备注信息" 
                  />
                </el-form-item>

                <el-button 
              type="primary" 
              @click="submitUserInfo" 
              :loading="submitting"
              class="submit-btn"
            >
              提交
            </el-button>
              </el-form>
            </div>
           
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup lang="ts" name="MobileAttachmentIndex">
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Picture } from '@element-plus/icons-vue'
  import service from '@/utils/request'
  
  // 声明全局pcaData类型
  declare global {
    interface Window {
      pcaData: any
    }
  }
  
  // 响应式数据
  const loading = ref(false)
  const loadingMore = ref(false)
  const dataList = ref<any[]>([])
  const hasMore = ref(true)
  const showViewer = ref(false)
  const previewUrls = ref<string[]>([])
  const previewIndex = ref(0)
  const showUserDialog = ref(false)
  const submitting = ref(false)
  const userFormRef = ref()
  
  // 省市区数据
  const provinceList = ref<string[]>([])
  const cityList = ref<string[]>([])
  const districtList = ref<string[]>([])
  
  // userForm 增加索引签名，便于动态赋值
  const userForm: { [key: string]: string } = reactive({
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    address: '',
    remark: ''
  })
  
  // 表单验证规则
  const formRules = {
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入电话号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    address: [
      { required: true, message: '请输入详细地址', trigger: 'blur' }
    ]
  }
  
  // 分页参数
  const pageParams = reactive({
    page: 1,
    limit: 100,
    name: ''
  })
  
  // 获取数据列表
  const getDataList = async (isLoadMore = false) => {
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      loading.value = true
      pageParams.page = 1
      dataList.value = []
    }
  
        try {
      const params = {
        page: pageParams.page,
        limit: pageParams.limit,
        order: 'id',
        asc: true
      }

      const response = await service.get('/sys/attachment/pageAll', { params })
      // 业务数据在 response.data 里
      if (response.data.code === 0) {
        const { list, total } = response.data
        
        if (isLoadMore) {
          dataList.value.push(...list)
        } else {
          dataList.value = list
        }
        
        // 判断是否还有更多数据
        hasMore.value = dataList.value.length < total
      } else {
        // 业务错误信息同样在 response.data
        ElMessage.error(response.data.msg || '获取数据失败')
      }
    } catch (error) {
      ElMessage.error('网络错误，请稍后重试')
    } finally {
      loading.value = false
      loadingMore.value = false
    }
  }
  
  // 加载更多
  const loadMore = () => {
    if (!hasMore.value || loadingMore.value) return
    pageParams.page++
    getDataList(true)
  }
  
  // 预览图片
  const previewImage = async (item: any, index: number) => {
    // 只有第一张图片可以点击，显示用户信息弹框
    if (index === 0) {
      showUserDialog.value = true
      // 在弹窗打开时初始化省市区数据
      await initPcaData()
    }
    // 其他图片点击时不做任何操作
  }
  
  // 处理图片加载错误
  const handleImageError = () => {
    // 图片加载失败时的处理
  }
  
  // 初始化省市区数据
  const initPcaData = async () => {
    try {
      const data = await import('@/components/ma-address/pca.json')
      const pcaData = data.default
      console.log('pca data:', pcaData)
      console.log('pca keys:', Object.keys(pcaData))
      
      // 强制更新响应式数据
      provinceList.value = []
      await nextTick()
      provinceList.value = [...Object.keys(pcaData)]
      console.log('provinceList:', provinceList.value)
      console.log('provinceList count:', provinceList.value.length)
      
      // 更新处理函数中的pca引用
      window.pcaData = pcaData
    } catch (error) {
      console.error('导入pca数据失败:', error)
    }
  }
  
  // 处理省份变化
  const handleProvinceChange = (event: Event) => {
    const province = (event.target as HTMLSelectElement).value
    console.log('选择省份:', province)
    userForm.city = ''
    userForm.district = ''
    cityList.value = []
    districtList.value = []
    
    if (province && window.pcaData && window.pcaData[province]) {
      cityList.value = Object.keys(window.pcaData[province])
      console.log('城市列表:', cityList.value)
    }
  }
  
  // 处理城市变化
  const handleCityChange = (event: Event) => {
    const city = (event.target as HTMLSelectElement).value
    console.log('选择城市:', city)
    userForm.district = ''
    districtList.value = []
    
    if (city && userForm.province && window.pcaData && window.pcaData[userForm.province][city]) {
      districtList.value = window.pcaData[userForm.province][city]
      console.log('区县列表:', districtList.value)
    }
  }
  
  // 关闭用户信息弹框
  const closeUserDialog = () => {
    // 重置表单
    Object.keys(userForm).forEach(key => {
      userForm[key] = ''
    })
    // 清除表单验证状态
    if (userFormRef.value) {
      userFormRef.value.clearValidate()
    }
    // 重置省市区列表
    cityList.value = []
    districtList.value = []
  }
  
  // 提交用户信息
  const submitUserInfo = async () => {
    try {
      await userFormRef.value.validate()
      submitting.value = true
      
      const response = await service.post('/user/info/save', userForm)
      // 业务数据在 response.data 里
      if (response.data.code === 0) {
        ElMessage.success('提交成功')
        showUserDialog.value = false
        // 重置表单
        Object.keys(userForm).forEach(key => {
          userForm[key] = ''
        })
        // 重置省市区列表
        cityList.value = []
        districtList.value = []
      } else {
        ElMessage.error(response.data.msg || '提交失败')
      }
    } catch (error) {
      // TypeScript 4.4+，catch error 默认 unknown 类型，需判断
      if (error instanceof Error) {
        ElMessage.error(error.message)
      } else {
        ElMessage.error('提交失败，请稍后重试')
      }
    } finally {
      submitting.value = false
    }
  }
  

  
  // 页面加载时获取数据
  onMounted(() => {
    getDataList()
  })
  </script>
  
  <style scoped lang="scss">
  .mobile-attachment-container {
    background-color: #f5f5f5;
    padding: 0;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 9999;
    overflow-y: auto;
  }
  
  .image-list {
    display: flex;
    flex-direction: column;
    padding: 0;
    gap: 0;
    margin: 0;
  }
  
  .image-item {
    background: white;
    overflow: hidden;
    width: 100%;
    height: auto;
    position: relative;
    margin: 0;
    padding: 0;
    
    &.clickable {
      cursor: pointer;
      
      &:active {
        transform: scale(0.98);
      }
    }
    
    &.non-clickable {
      cursor: default;
      opacity: 0.8;
      
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.1);
        pointer-events: none;
      }
    }
  }
  
  .image-wrapper {
    position: relative;
    width: 100%;
    height: auto;
    overflow: hidden;
    background-color: #f8f8f8;
    margin: 0;
    padding: 0;
    
    .el-image {
      width: 100%;
      height: auto;
      object-fit: contain;
      display: block;
    }
    
    .image-error {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #999;
      font-size: 14px;
      
      .el-icon {
        font-size: 24px;
        margin-bottom: 8px;
      }
    }
  }
  
  .load-more {
    text-align: center;
    margin-top: 10px;
    padding: 8px 0;
  }
  
  // 用户信息弹框样式
  .user-dialog {
    .el-overlay {
      background-color: rgba(0, 0, 0, 0.5);
    }
    
    .el-dialog {
      border-radius: 12px;
      overflow: hidden;
      margin: 0 auto !important;
      max-height: 100vh;
      background: transparent;
      box-shadow: none;
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
    
    .el-dialog__body {
      padding: 0;
    }
    
    .el-dialog__header {
      display: none;
    }
  }
  
  .dialog-content {
    display: flex;
    flex-direction: column;
    height: 100vh;
    border-radius: 12px;
    overflow: hidden;
  }
  
  .image-section {
    flex: 0 0 15%;
    background: linear-gradient(135deg, #ff4757, #ff3742);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 15px;
    position: relative;
    border-radius: 12px 12px 0 0;
    
    .service-image {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }
  }
  
  .form-section {
    flex: 1;
    background: white;
    padding: 5px 5px;
    overflow-y: auto;
    min-height: 85%;
    border-radius: 0 0 12px 12px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    
    .form-content {
      flex: 1;
      overflow-y: auto;
      padding-bottom: 20px;
    }
    
    .el-form {
      display: flex;
      flex-direction: column;
    }
    
    .el-form-item {
      margin-bottom: 10px;
      flex-shrink: 0;
    }
    
    .el-form-item__label {
      white-space: nowrap;
      overflow: visible;
      text-overflow: unset;
    }
    
    .el-input__wrapper {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
    }
    
    .el-input__inner {
      overflow: visible;
      text-overflow: unset;
      white-space: normal;
    }
    
    .el-textarea__inner {
      resize: none;
      overflow: visible;
      text-overflow: unset;
      white-space: normal;
    }
    
    .region-inputs {
      display: flex;
      gap: 8px;
      
      .el-input,
      .el-select {
        flex: 1;
      }
      
      .el-select .el-input__wrapper {
        height: 40px;
      }
    }
    
    .submit-btn {
      width: 100%;
      height: 44px;
      font-size: 16px;
      margin-top: 15px;
      background: #ff4757;
      border-color: #ff4757;
      flex-shrink: 0;
      
      &:hover {
        background: #ff3742;
        border-color: #ff3742;
      }
    }
  }
  

  </style>